package Follow

import (
	"FromNowOnPromote/博客系统/Tblog/controllers"
	"FromNowOnPromote/博客系统/Tblog/models"
	"FromNowOnPromote/博客系统/Tblog/models/User"
	"FromNowOnPromote/博客系统/Tblog/redis"
	"encoding/json"
	"fmt"
	"strconv"
)

type UserFollow struct {
	controllers.MainController
}

type FollowRespon struct {
	Uuid         int
	UserName     string
	Introduction string
	Email        string
	IconUrl      string
}

func (this *UserFollow) Get() {
	uuid := this.Ctx.GetCookie("uuid")
	rd := redis.R.Conn
	defer rd.Close()
	userid, _ := rd.Get(uuid)
	if userid == "" {
		body := map[string]interface{}{"code": 300, "data": "请求异常"}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}
	//查找关注用户的id
	ms, err1 := searchfollow(userid)
	if err1 != nil {
		body := map[string]interface{}{"code": 301, "data": "请求异常"}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}
	db := models.ConnDb()
	defer db.Close()
	var tbusers []User.TbUser
	var frs []FollowRespon
	for _, i := range ms {
		var tbuser User.TbUser
		uid, _ := strconv.Atoi(i)
		db.Where("uuid = ?", uid).Find(&tbuser)
		tbusers = append(tbusers, tbuser)
	}
	b, err2 := json.Marshal(tbusers)
	if err2 != nil {
		body := map[string]interface{}{"code": 302, "data": "服务器异常"}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}
	err3 := json.Unmarshal(b, &frs)
	if err3 != nil {
		body := map[string]interface{}{"code": 303, "data": "服务器异常"}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}
	body := map[string]interface{}{"code": 200, "data": frs}
	this.Data["json"] = body
	this.ServeJSON()
}

func searchfollow(uid string) ([]string, error) {
	fl := redis.R.FollowConn
	ms, err := fl.HKeys(uid)
	if err != nil {
		return nil, err
	}
	return ms, nil
}

type UnFollow struct {
	controllers.MainController
}

type PSD struct {
	Uuid string `json:"uuid"`
}

func (this *UnFollow) Post() {
	uuid := this.Ctx.GetCookie("uuid")
	rd := redis.R.Conn
	defer rd.Close()
	userid, _ := rd.Get(uuid)
	if userid == "" {
		body := map[string]interface{}{"code": "300", "data": "请求异常"}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}
	//解析json获取要取消关注的id
	var p PSD
	r := this.Ctx.Request
	decoder := json.NewDecoder(r.Body)
	err := decoder.Decode(&p)
	if err != nil {
		body := map[string]interface{}{"code": "300", "data": "请求异常"}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}
	fl := redis.R.FollowConn
	defer fl.Close()
	fmt.Println(p.Uuid)
	_, err1 := fl.HDel(userid, p.Uuid)
	if err1 != nil {
		body := map[string]interface{}{"code": "300", "data": "请求异常"}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}
	body := map[string]interface{}{"code": "200", "data": "操作成功"}
	this.Data["json"] = body
	this.ServeJSON()
}
